using System;
using System.Collections;
using System.Text;
using System.Web;
using Sedna.Core.Common;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;

namespace Sedna.Core.pages.Actions
{
	/// <summary>
	/// This action prepares exception to be displayed on SessionException page
	/// </summary>
	public class SessionExceptionPrepareAction: AbstractAction
	{
        private String exceptionCodePath;
        private IList exceptionsToSkip;

	    public string ExceptionCodePath
	    {
	        set { exceptionCodePath = value; }
	    }

	    public IList ExceptionsToSkip
	    {
	        set { exceptionsToSkip = value; }
	    }

	    public override IActionResult Execute(IExecutionContext executionContext)
		{
	        Exception exception = (Exception)executionContext.GetScopedValue("infrastructure.LastException", Scope.Session);
			string stackTrace = PrepareStackTrace(exception);
	        Exception innerException = SednaException.ExtractInnerException(exception, exceptionsToSkip);
			int exceptionCode = -1;
			SednaException coreIMSEEException = innerException as SednaException;
			if(coreIMSEEException != null)
			{
                exceptionCode = coreIMSEEException.ExceptionCode;
			}

            executionContext.SetPropertyValue(exceptionCodePath, exceptionCode);
			executionContext.SetScopedValue("infrastructure.LastStackTrace", stackTrace, Scope.Session);
			return new ActionResult(successStatus);
		}

		private string PrepareStackTrace(Exception ex)
		{
		    StringBuilder sb = new StringBuilder();
			for(; ex != null && ex != ex.InnerException; ex = ex.InnerException)
			{
                sb.Append(ex.GetType());
                sb.Append("\n");
                sb.Append(ex.Message);
                sb.Append("\n");
                sb.Append(ex.StackTrace);
                sb.Append("\n\n-----------------------------\n\n");
			}
            return sb.ToString();
		}
	}
}
